package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveWordEntity;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveWordsMonitorEntity;
import com.pactera.madp.cp.api.dto.sensitive.ReqSensitiveWordsMonitorDto;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.sensitive.SensitiveWordMonitorDetailsVO;
import com.pactera.madp.cp.api.vo.sensitive.SensitiveWordMonitorPageVO;
import com.pactera.madp.cp.common.util.PageUtil;
import com.pactera.madp.cp.common.util.ali.AliyunOssUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.sensitiveword.SensitiveWordsMonitorMapper;
import com.pactera.madp.cp.service.ISensitiveWordService;
import com.pactera.madp.cp.service.ISensitiveWordsMonitorService;
import org.jsoup.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description:敏感词监控 - 列表
 * @author: Huayu
 * @time: 2021/2/4 10:33
 */
@Service
public class SensitiveWordsMonitorServiceImpl extends ServiceImpl<SensitiveWordsMonitorMapper, SensitiveWordsMonitorEntity> implements ISensitiveWordsMonitorService {

    private Logger logger = LoggerFactory.getLogger(SensitiveWordsMonitorServiceImpl.class);

    @Resource
    private SensitiveWordsMonitorMapper sensitiveWordsMonitorMapper;
    @Autowired
    private ISensitiveWordService sensitiveWordServiceImpl;

    @Override
    public Page<SensitiveWordMonitorPageVO> handle(ReqSensitiveWordsMonitorDto reqSensitiveWordsMonitorDto, Page page) {
        //处理请求参数
        return handleParams(reqSensitiveWordsMonitorDto,page);
    }

    @Override
    public SensitiveWordsMonitorEntity getSensitiveWordMonitorById(String sensitiveWordsMonitorId) {
        QueryWrapper<SensitiveWordsMonitorEntity> sensitiveWordsMonitorEntityQueryWrapper = new QueryWrapper();
        sensitiveWordsMonitorEntityQueryWrapper.select("chat_content,source");
        sensitiveWordsMonitorEntityQueryWrapper.eq("id",sensitiveWordsMonitorId);
        return this.baseMapper.selectOne(sensitiveWordsMonitorEntityQueryWrapper);
    }


    @Override
    public SensitiveWordMonitorDetailsVO contentFormat(JSONObject jsonObject1) {
        //文字
        SensitiveWordMonitorDetailsVO vo = new SensitiveWordMonitorDetailsVO();
        String content = jsonObject1.getString("msgContent");
        if(content != null && !content.equals("")){
            vo.setContent(JSONObject.parseObject(content));
        }
        vo.setSender(jsonObject1.getString("sender"));
        vo.setIsTrigger(jsonObject1.getIntValue("isTrigger"));
        vo.setType(jsonObject1.getIntValue("msgType"));
        vo.setSendTime(jsonObject1.getString("sendTime"));
        return vo;
    }



    @Override
    public void createSensitiveWordMonitors(Map map) {
        List<SensitiveWordsMonitorEntity> monitors = JSONArray.parseArray(JSONUtil.toJsonStr(map.get("createMonitors")), SensitiveWordsMonitorEntity.class);
        monitors.forEach(m->{
            Integer i = this.baseMapper.insert(m);
            if(i > 0){
                logger.info("会话信息监测敏感词触发入表成功");
            }else{
                logger.info("会话信息监测敏感词触发入表失败");
            }
        });

    }


    private Map<String, Object> contentItemFormat(JSONObject jsonObject1) {
        JSONArray jsonArray = jsonObject1.getJSONArray("item");
        String type = null;
        List<Map<String, Object>> mapDataList = new ArrayList<Map<String, Object>>();
        Map<String, Object> mapDataList2 = new HashMap<String,Object>();
        for (int i = 0; i < jsonArray.size(); i++) {
            Map<String, Object> mapData = new HashMap<String,Object>();
            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
            type = jsonObject2.getString("type");
            switch (type) {
                case "text":
                    mapData.put("content", "混合消息-文本");
                    break;
                case "image":
                case "emotion":
                    String ossPath = jsonObject1.getString("ossPath");
                    if (ossPath != null && !ossPath.equals("")) {
                        mapData.put("ossFullPath", AliyunOssUtils.getUrl(ossPath));
                        break;
                    }
            }
            mapDataList.add(mapData);
        }
        mapDataList2.put("item",mapDataList);
        return mapDataList2;
    }


    private Page<SensitiveWordMonitorPageVO> handleParams(ReqSensitiveWordsMonitorDto reqSensitiveWordsMonitorDto, Page page) {

        SubPage subPage = new SubPage();
        QueryWrapper<SensitiveWordsMonitorEntity> queryWrapper = new QueryWrapper<SensitiveWordsMonitorEntity>();
        queryWrapper.select("id", "sensitive_word_name", "source", "trigger_name", "receiver_name", "trigger_time");
        queryWrapper.eq("corp_id", CorpContextHolder.getCorpId());

//        Integer pageNum = reqSensitiveWordsMonitorDto.getPage();
//        pageNum = (pageNum == null || pageNum.equals("")) ? 1 : pageNum;
//        Integer perPage = reqSensitiveWordsMonitorDto.getPerPage();
//        perPage = (perPage == null || perPage.equals("")) ? 10 : perPage;
//        reqSensitiveWordsMonitorDto.setPage(pageNum);
//        reqSensitiveWordsMonitorDto.setPerPage(perPage);
        //公司信息
//        reqSensitiveWordsMonitorDto.setCorpId(AccountService.getCorpId());
        //敏感词分组
        if(reqSensitiveWordsMonitorDto.getIntelligentGroupId() != null && !reqSensitiveWordsMonitorDto.getIntelligentGroupId().equals("")){
            List<SensitiveWordEntity> sensitiveWordEntityList = sensitiveWordServiceImpl.getSensitiveWordList(reqSensitiveWordsMonitorDto.getIntelligentGroupId());
            StringBuilder sb =  new StringBuilder();
            String sensitiveIdStr = null;
            for (SensitiveWordEntity sensitiveWordEntity:
            sensitiveWordEntityList) {
                sensitiveIdStr = sensitiveWordEntity.getId().toString();
                sensitiveIdStr = sensitiveIdStr + ",";
                sb.append(sensitiveIdStr);
            }
            if (sb.length() == 0) {
                return new Page<>();
            }
            sensitiveIdStr = sb.substring(0, sb.length() - 1);
            reqSensitiveWordsMonitorDto.setSensitiveWordIds(sensitiveIdStr);
        }
        //员工信息
        /*if(reqSensitiveWordsMonitorDto.getEmployeeId() != null && reqSensitiveWordsMonitorDto.getEmployeeId().length() > 0){
            String[] employeeIdArr = reqSensitiveWordsMonitorDto.getEmployeeId().split(",");
        }*/

        if(reqSensitiveWordsMonitorDto.getSensitiveWordIds()!=null && !reqSensitiveWordsMonitorDto.getSensitiveWordIds().equals("")){
            queryWrapper.in("sensitive_word_id", reqSensitiveWordsMonitorDto.getSensitiveWordIds());
        }
        if(!StringUtil.isBlank(reqSensitiveWordsMonitorDto.getEmployeeId())){
            queryWrapper.in("trigger_id", reqSensitiveWordsMonitorDto.getEmployeeId());
            queryWrapper.eq("source","2");
        }
        if(reqSensitiveWordsMonitorDto.getWorkRoomId()!=null && !reqSensitiveWordsMonitorDto.getWorkRoomId().equals("")){
            queryWrapper.in("receiver_id", reqSensitiveWordsMonitorDto.getWorkRoomId());
            queryWrapper.eq("receiver_type","3");
        }
        if(reqSensitiveWordsMonitorDto.getTriggerStart()!=null && reqSensitiveWordsMonitorDto.getTriggerEnd()!=null){
            queryWrapper.ge("trigger_time", reqSensitiveWordsMonitorDto.getTriggerStart()+" 00:00:00");
            queryWrapper.le("trigger_time", reqSensitiveWordsMonitorDto.getTriggerEnd()+" 23:59:59");
        }
        queryWrapper.orderByDesc("trigger_time");
        List<Map<String, Object>> maps = listMaps(queryWrapper);
        List<SensitiveWordMonitorPageVO> vos = new LinkedList<>();
        maps.forEach(r->{
            SensitiveWordMonitorPageVO vo = new SensitiveWordMonitorPageVO();
            BeanUtil.copyProperties(r,vo);
            vo.setSourceType(vo.getSource() == 1 ? "客户" :"员工" );
            vo.setTriggeringScenarios("聊天");
            vos.add(vo);
        });

        Page<SensitiveWordMonitorPageVO> split = PageUtil.split(vos, (int) page.getCurrent(), (int) page.getSize());

        return split;
    }
}
